// 高德地图API配置
const AMAP_CONFIG = {
  key: process.env.VUE_APP_AMAP_KEY || "93a2bc421fe24dc7e31c71276380b0b3", // 从环境变量获取API密钥
  version: "2.0",
  plugins: [
    "AMap.Geocoder",
    "AMap.PlaceSearch",
    "AMap.Polygon",
    "AMap.MouseTool",
  ],
};

// 地图工具函数
export const loadAMapScript = () => {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      resolve(window.AMap);
      return;
    }

    const script = document.createElement("script");
    script.src = `https://webapi.amap.com/maps?v=${AMAP_CONFIG.version}&key=${
      AMAP_CONFIG.key
    }&plugin=${AMAP_CONFIG.plugins.join(",")}`;
    
    script.onload = () => {
      // 检查AMap是否真正加载成功
      if (window.AMap) {
        resolve(window.AMap);
      } else {
        reject(new Error('AMap script loaded but AMap object not found'));
      }
    };
    
    script.onerror = (error) => {
      reject(new Error(`Failed to load AMap script: ${error.message || 'Network error'}`));
    };
    
    // 设置超时
    setTimeout(() => {
      if (!window.AMap) {
        reject(new Error('AMap script loading timeout'));
      }
    }, 10000);
    
    document.head.appendChild(script);
  });
};

// 坐标验证
export const validateCoordinates = (coordinates) => {
  if (!Array.isArray(coordinates)) return false;

  return coordinates.every(
    (coord) =>
      Array.isArray(coord) &&
      coord.length === 2 &&
      typeof coord[0] === "number" &&
      typeof coord[1] === "number" &&
      coord[0] >= -180 &&
      coord[0] <= 180 &&
      coord[1] >= -90 &&
      coord[1] <= 90
  );
};

// 计算多边形中心点
export const getPolygonCenter = (coordinates) => {
  if (!Array.isArray(coordinates) || coordinates.length === 0) {
    return [116.397428, 39.90923]; // 默认北京坐标
  }

  // 过滤掉无效坐标
  const validCoordinates = coordinates.filter(coord => {
    if (!Array.isArray(coord) || coord.length !== 2) return false;
    const [lng, lat] = coord;
    // 检查是否为有效坐标：不是NaN，不是0，且在合理范围内
    if (isNaN(lng) || isNaN(lat) || lng === 0 || lat === 0) return false;
    if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return false;
    return true;
  });

  // 如果没有有效坐标，返回默认北京坐标
  if (validCoordinates.length === 0) {
    return [116.397428, 39.90923];
  }

  let sumLng = 0;
  let sumLat = 0;

  validCoordinates.forEach((coord) => {
    sumLng += coord[0];
    sumLat += coord[1];
  });

  return [sumLng / validCoordinates.length, sumLat / validCoordinates.length];
};

// 节流函数
export const throttle = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

export default {
  loadAMapScript,
  validateCoordinates,
  getPolygonCenter,
  throttle,
};
